<?php

namespace app\admin\service;

use app\admin\validate\UserLevelValidate;
use support\spark\exception\ApiException;
use support\spark\model\user\UserLevel;

class UserLevelService
{
    /**
     * 用户等级列表
     * @param $param
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function getList($param)
    {
        $limit = $param['limit'];
        $title = $param['title'];
        $where = [];

        if (!empty($title)) {
            $where[] = ['title', 'like', '%' . $title . '%'];
        }

        $userLevelModel = new UserLevel();
        $list = $userLevelModel->getPaginateList($where, ['*'], ['level' => 'asc'], [], $limit);
        return dataReturn(0, 'success', $list);
    }

    /**
     * 增加用户等级
     * @param $param
     * @return array
     */
    public function addUserLevel($param)
    {
        if (isset($param['file'])) {
            unset($param['file']);
        }
        // 检验完整性
        $validate = new UserLevelValidate();
        if (!$validate->check($param)) {
            throw  new  ApiException($validate->getError(), -1);
        }
        $userLevelModel = new UserLevel();
        $has = $userLevelModel->checkUnique([
            'level' => $param['level']
        ]);
        if (!empty($has)) {
            throw  new  ApiException('该等级已经存在', -2);
        }
        $param['create_time'] = now();
        $param['update_time'] = now();
        $userLevelModel->insertOne($param);
        return dataReturn(0, '添加成功');
    }

    /**
     * 编辑用户等级
     * @param $param
     * @return array
     */
    public function editUserLevel($param)
    {
        if (isset($param['file'])) {
            unset($param['file']);
        }

        // 检验完整性
        $validate = new UserLevelValidate();
        if (!$validate->check($param)) {
            throw  new  ApiException($validate->getError(), -1);
        }
        $userLevelModel = new UserLevel();

        $where[] = ['id', '<>', $param['id']];
        $where[] = ['level', '=', $param['level']];
        $has = $userLevelModel->checkUnique($where);
        if (!empty($has)) {
            throw  new  ApiException('该等级已经存在', -2);
        }
        $userLevelModel->updateById($param, $param['id']);
        return dataReturn(0, '编辑成功');
    }
}